package topofstack.networkserverutils.net;

import java.io.BufferedReader;
import java.io.StringReader;

import topofstack.networkserverutils.bean.PingInfo;
import topofstack.networkserverutils.util.ShellEmulator;

public class Ping {
	
	public static final int PACKET_COUNT = 5;
	
	private static final int PACKET_TRANSMITTED_INDEX = 0;
	private static final int PACKET_RECEIVED_INDEX = 4;
	private static final int TIME_INDEX = 13;
	
	public static PingInfo get(String url) {
		String command = "ping -c " + PACKET_COUNT + " " + url;
		String result = ShellEmulator.query(command);
		
		return parse(result);
	}
	
	private static PingInfo parse(String input) {
		if(input == null)
			return null;
		
		BufferedReader reader = new BufferedReader(new StringReader(input));
		
		String line;
		try {
			while((line = reader.readLine()) != null) {
				if(line.contains("packets transmitted")) {
					String[] contents = line.split("[\\W]");
					
					int transmitted = Integer.parseInt(contents[PACKET_TRANSMITTED_INDEX]);
					int received = Integer.parseInt(contents[PACKET_RECEIVED_INDEX]);
					String time = contents[TIME_INDEX];
					
					PingInfo info = new PingInfo(transmitted, received, time);
					return info;
				}
			}
		}
		catch(Exception exception) {
			exception.printStackTrace();
			return null;
		}
		
		return null;
	}
}
